package com.zhongjian.technologycal.mall.activity.personal.fragment;

import android.content.Intent;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.widget.ListView;

import com.google.gson.Gson;
import com.scwang.smartrefresh.layout.api.RefreshLayout;
import com.scwang.smartrefresh.layout.listener.OnLoadmoreListener;
import com.scwang.smartrefresh.layout.listener.OnRefreshListener;
import com.zhongjian.technologycal.mall.R;
import com.zhongjian.technologycal.mall.adapter.FansListAdaper;
import com.zhongjian.technologycal.mall.base.BaseFragment;
import com.zhongjian.technologycal.mall.bean.FansBeans;
import com.zhongjian.technologycal.mall.net.HttpRetrofitClient;
import com.zhongjian.technologycal.mall.utils.NetWorkUtils;
import com.zhongjian.technologycal.mall.utils.ToastUitl;
import com.zhongjian.technologycal.mall.utils.UserUtils;

import org.json.JSONArray;
import org.json.JSONObject;

import java.util.ArrayList;
import java.util.List;

import butterknife.BindView;
import okhttp3.ResponseBody;
import rx.Subscriber;

/**
 * Created by wei on 2017/12/15.
 */

public class RedFansFragment extends BaseFragment {
    public static final String CATEGORY_NAME = "com.nanchen.aiyagirl.module.category.CategoryFragment.CATEGORY_NAME";
    @BindView(R.id.fans_listview)
    ListView fans_listview;
    private FansListAdaper fansListAdaper;
    private List<FansBeans> listItems = new ArrayList<>();
    @BindView(R.id.list_refresh)
    RefreshLayout list_refresh;
    private int page = 0;
    private int pageNum = 10;
    private Handler handler = new Handler() {
        @Override
        public void handleMessage(Message msg) {
            super.handleMessage(msg);
            switch (msg.what) {
                case 0:
                    fansListAdaper.notifyDataSetChanged();
                    break;
            }
        }
    };

    @Override
    protected void initView() {
        initViewRequest();
        fansListAdaper = new FansListAdaper(getActivity(), listItems);
        fans_listview.setAdapter(fansListAdaper);
        list_refresh.setOnRefreshListener(new OnRefreshListener() {
            @Override
            public void onRefresh(RefreshLayout refreshlayout) {
                refreshlayout.getLayout().postDelayed(new Runnable() {
                    @Override
                    public void run() {
                        page = 0;
                        initViewRequest();
                        list_refresh.finishRefresh();
                    }
                }, 1000);
            }
        });
        list_refresh.setOnLoadmoreListener(new OnLoadmoreListener() {
            @Override
            public void onLoadmore(RefreshLayout refreshlayout) {
                list_refresh.getLayout().postDelayed(new Runnable() {
                    @Override
                    public void run() {
                        page++;
                        initViewRequest();
                        list_refresh.finishLoadmore();
                    }
                }, 1000);
            }
        });

    }

    @Override
    protected int getLayoutResource() {
        return R.layout.fragment_red_fans;
    }


    public static RedFansFragment newInstance(String mCategoryName) {
        RedFansFragment categoryFragment = new RedFansFragment();
        Bundle bundle = new Bundle();
        bundle.putString(CATEGORY_NAME, mCategoryName);
        categoryFragment.setArguments(bundle);
        return categoryFragment;
    }

    @Override
    public void initPresenter() {

    }

    /**
     * 网络数据请求
     */
    private void initViewRequest() {
        if (!NetWorkUtils.isNetConnected(getActivity())) {
            ToastUitl.showShort(R.string.no_net);
            return;
        } else {
            HttpRetrofitClient.getInstance(getActivity())
                    .getUrlRequestFansList(UserUtils.getUserToken(),
                            "Red", page, pageNum, new Subscriber<ResponseBody>() {
                                @Override
                                public void onStart() {
                                    super.onStart();
                                }

                                @Override
                                public void onCompleted() {

                                }

                                @Override
                                public void onError(Throwable e) {

                                }

                                @Override
                                public void onNext(ResponseBody responseBody) {
                                    try {
                                        Gson gson = new Gson();
                                        JSONObject jsonObject = new JSONObject(responseBody.string());
                                        if(jsonObject.getString("error_code").equals("0")){
                                            JSONArray jsonFans = jsonObject.optJSONArray("data");
                                            List<FansBeans> forList = new ArrayList<>();
                                            for (int i = 0; i < jsonFans.length(); i++) {
                                                FansBeans fansBeans = gson.fromJson(jsonFans.optString(i).toString(), FansBeans.class);
                                                forList.add(fansBeans);
                                                if(forList.size() < 10){
                                                    list_refresh.setEnableLoadmore(true);
                                                }
                                            }
                                            setData(forList);
                                        }else if(jsonObject.getString("error_code").equals("3")){
                                            Intent intent = new Intent();
                                            intent.setAction("com.broadcast.info_out_line");
                                            getActivity().sendBroadcast(intent);

                                        }else{
                                            ToastUitl.showShort(jsonObject.getString("error_code"));
                                        }



                                    } catch (Exception e) {
                                        e.printStackTrace();
                                    }


                                }
                            });
        }
    }

    private void setData(List<FansBeans> foreshowList) {
        if (page == 0) {
            listItems.clear();
        }
        for (FansBeans vo : foreshowList) {
            listItems.add(vo);
        }
        handler.sendEmptyMessage(0);

    }
}
